# Default url mappings are:
#  a controller called Main is mapped on the root of the site: /
#  a controller called Something is mapped on: /something
# If you want to override this, add a line like this inside the class
#  map '/otherurl'
# this will force the controller to be mounted on: /otherurl

require 'connection_pool_fibered'
require File.dirname(__FILE__) + '/../../../setup_db_opts.rb'
require 'mysql' # for the 'old_school' example

class MainController < Ramaze::Controller
  layout '/page'

  SLOW_QUERY = "select count(*) from user_sessions"
  FAST_QUERY = "select count(*) from users" # these just happen to be fast and slow
  
  # the index action is called automatically when no other action is specified
  @@count = 3
  def mixed_new_school
    setup
    count = @@count 
    @@count += 1
    if count % 5 == 0 # 1 in x
	query = 'long'
       $DB.exec_when_available(SLOW_QUERY) {|columns, rows| } 
    else
       query = 'short'
	$DB.exec_when_available(FAST_QUERY) {|columns, rows|} 
    end
    @title = "Welcome to Ramaze #{@@count} #{count}! #{query}"
  end

  def short_new_school
    setup
    $DB.exec_when_available(FAST_QUERY) {|columns, rows|}
    'did short new school'
  end
  
  def long_new_school
    setup
    $DB.exec_when_available(SLOW_QUERY) {|columns, rows|}
    'did long new school'
  end

  def text_only
    'abc'
  end

  def mixed_old_school
     setup
     count = @@count
     @@count += 1
     if count % 5 == 0 # 1 in x
        speed = 'slow'
        query = SLOW_QUERY
     else
        speed = 'fast'
	query = FAST_QUERY
     end

     res = $db_old.query(query)
     res.free
     "did #{speed} query" 
  end

  def short_old_school
	$db_old.query(FAST_QUERY).free
        'did short old school'
  end

  def long_old_school
	$db_old.query(SLOW_QUERY).free
        'did long old school'
  end

  private

  def setup
    $DB ||= ConnectionPool.new 20, $opts  # ugh! necessary since we have to already be in the eVent loop to start these, which is like a mongrel 'first serve' thing :)  

    # and the 'bad' example
    begin
	$db_old ||= Mysql.real_connect $opts[:target], $opts[:username], $opts[:password], $opts[:database]
    rescue Mysql::Error => e
      puts "Error code: #{e.errno}"
      puts "Error message: #{e.error}"
      puts "Error SQLSTATE: #{e.sqlstate}" if e.respond_to?("sqlstate")
   end
  end

end
